<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <title>BellmanFord和SPFA算法详解 - L_B__</title><meta name="referrer" content="no-referrer">
<meta name="description" content="BellmanFord和SPFA算法详解"><meta property="og:title" content="BellmanFord和SPFA算法详解" />
<meta property="og:description" content="BellmanFord和SPFA算法详解" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://acking-you.github.io/posts/bellmanford%E5%92%8Cspfa%E7%AE%97%E6%B3%95%E8%AF%A6%E8%A7%A3/" /><meta property="og:image" content="https://acking-you.github.io/logo.png"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2022-02-07T00:00:00+00:00" />
<meta property="article:modified_time" content="2022-02-07T00:00:00+00:00" />

<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://acking-you.github.io/logo.png"/>

<meta name="twitter:title" content="BellmanFord和SPFA算法详解"/>
<meta name="twitter:description" content="BellmanFord和SPFA算法详解"/>
<meta name="application-name" content="FeelIt">
<meta name="apple-mobile-web-app-title" content="FeelIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="canonical" href="https://acking-you.github.io/posts/bellmanford%E5%92%8Cspfa%E7%AE%97%E6%B3%95%E8%AF%A6%E8%A7%A3/" /><link rel="prev" href="https://acking-you.github.io/posts/dijkstra%E7%AE%97%E6%B3%95%E6%A8%A1%E6%9D%BF%E8%AE%B2%E8%A7%A3/" /><link rel="next" href="https://acking-you.github.io/posts/%E6%95%B0%E6%8D%AE%E5%BA%93%E5%9F%BA%E7%A1%80/" /><link rel="stylesheet" href="/css/page.min.css"><link rel="stylesheet" href="/css/home.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "BellmanFord和SPFA算法详解",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/acking-you.github.io\/posts\/bellmanford%E5%92%8Cspfa%E7%AE%97%E6%B3%95%E8%AF%A6%E8%A7%A3\/"
        },"genre": "posts","keywords": "BellmanFord和SPFA算法详解","wordcount":  1482 ,
        "url": "https:\/\/acking-you.github.io\/posts\/bellmanford%E5%92%8Cspfa%E7%AE%97%E6%B3%95%E8%AF%A6%E8%A7%A3\/","datePublished": "2022-02-07T00:00:00+00:00","dateModified": "2022-02-07T00:00:00+00:00","publisher": {
            "@type": "Organization",
            "name": "作者"},"author": {
                "@type": "Person",
                "name": "作者"
            },"description": "BellmanFord和SPFA算法详解"
    }
    </script></head><body data-header-desktop="auto" data-header-mobile="auto"><script>(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="L_B__">L_B__</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 文章 </a><a class="menu-item" href="/tags/"> 标签 </a><a class="menu-item" href="/categories/"> 分类 </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-desktop">
                        <a href="#" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="L_B__">L_B__</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-mobile">
                        <a href="#" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="#" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">文章</a><a class="menu-item" href="/tags/" title="">标签</a><a class="menu-item" href="/categories/" title="">分类</a><div class="menu-item"><a href="javascript:void(0);" class="theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div></div>
    </div>
</header><div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single" data-toc="disable"><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img-blog.csdnimg.cn/img_convert/6a656bf83ac631cc9afaeaef07661809.png"
        data-srcset="https://img-blog.csdnimg.cn/img_convert/6a656bf83ac631cc9afaeaef07661809.png, https://img-blog.csdnimg.cn/img_convert/6a656bf83ac631cc9afaeaef07661809.png 1.5x, https://img-blog.csdnimg.cn/img_convert/6a656bf83ac631cc9afaeaef07661809.png 2x"
        data-sizes="auto"
        alt="https://img-blog.csdnimg.cn/img_convert/6a656bf83ac631cc9afaeaef07661809.png"
        title="BellmanFord和SPFA算法详解" /></div><div class="single-card" data-image="true"><h2 class="single-title animated flipInX">BellmanFord和SPFA算法详解</h2><div class="post-meta">
                <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>作者</a></span>&nbsp;<span class="post-category">出版于  <a href="/categories/%E7%AE%97%E6%B3%95%E6%9C%80%E7%9F%AD%E8%B7%AF%E9%97%AE%E9%A2%98/"><i class="far fa-folder fa-fw"></i>算法——最短路问题</a></span></div>
                <div class="post-meta-line"><span><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2022-02-07">2022-02-07</time></span>&nbsp;<span><i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 1482 字</span>&nbsp;
                    <span><i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 3 分钟</span>&nbsp;</div>
            </div>
            
            <hr><div class="details toc" id="toc-static"  data-kept="">
                    <div class="details-summary toc-title">
                        <span>目录</span>
                        <span><i class="details-icon fas fa-angle-right"></i></span>
                    </div>
                    <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#蓝桥杯--最短路">蓝桥杯&ndash;最短路</a></li>
    <li><a href="#bellman-ford的动态规划解决超时过三个">Bellman ford的动态规划解决(超时,过三个)</a></li>
    <li><a href="#bellman-ford按边遍历解决速度竟比spfa快我惊了">Bellman ford按边遍历解决(速度竟比SPFA快，我惊了)</a></li>
    <li><a href="#最终优化--spfa算法">最终优化&ndash;SPFA算法</a></li>
  </ul>
</nav></div>
                </div><div class="content" id="content"><h1 id="关于bellman-ford和spfa算法的详解">*关于Bellman ford和SPFA算法的详解</h1>
<blockquote>
<p>我是白嫖的leetcode会员，然后看了关于图单源最短路径的讲解，讲解的非常好(虽然没代码演示，但基本上一看思路就有了)。</p>
</blockquote>
<ul>
<li>
<p>为了让大家也白嫖到视频资源，我把视频上传到了YouTube(<strong>国内会有版权问题</strong>，发不出)
大家有能力上油管的建议去看看，否则这代码肯定是看不懂的。。。</p>
</li>
<li>
<p>视频链接：</p>
</li>
<li>
<p><a href="https://www.youtube.com/watch?v=gHt_yexTw7o&amp;list=PLf4URHiWMndm3NfqFdebywKPZ6Uktn9Sw&amp;index=5" target="_blank" rel="noopener noreffer">Bellman ford算法详解(两种方式及其优化)</a></p>
</li>
<li>
<p><a href="https://www.youtube.com/watch?v=JFh8guhfS8M&amp;list=PLf4URHiWMndnPWhsxpgUO5-d-pR6Qbxdn" target="_blank" rel="noopener noreffer">由Bellman ford算法的缺陷引出SPFA算法</a></p>
</li>
</ul>
<h1 id="适用性分析先看视频">适用性分析(先看视频)</h1>
<p><strong>Blellman ford算法</strong></p>
<ul>
<li>DP方法：以 <code>dp[i][j]</code> 表示选择最多 <code>i</code> 条边，从起点到 <code>j</code> 的最短距离。每次的更新依赖于上一行 <code>dp[i-1][j]</code> 的答案，故可滚动数组优化为一维数组。时间复杂度O(N^3)</li>
<li>多次遍历边的更新方法：提前记录好哪两个结点有边，每进行一次整个边的遍历，就相当于完成了最多选择一条边到达目的地的最短距离的效果。平均时间复杂度 <code>O(N*V)</code>（V是边的个数，极端情况下会掉到 <code>O(N*N*V)</code>的复杂度，因为最多是可以进行 <code>N-1</code> 次循环的)</li>
</ul>
<blockquote>
<p>很明显无论是哪种方式实现，最终都是依赖选择多少条边的结果，所以该算法<strong>适用于指定最多经过k条边的最短路径题目</strong>。</p>
</blockquote>
<ul>
<li>正好有道例题适合他 <a href="https://leetcode-cn.com/problems/cheapest-flights-within-k-stops/" target="_blank" rel="noopener noreffer">K 站中转内最便宜的航班</a></li>
</ul>
<p><strong>SPFA算法</strong></p>
<ul>
<li>这个算法只是Bellman ford算法的再优化，使得每次选择的边的关系达到最优，大大减少了边的遍历次数,时间复杂度较为稳定(相对Bellmanford稳定很多)的在 <code>O(N*V)</code>。</li>
</ul>
<blockquote>
<p>这个原本也是基于Bellmanford算法优化的，除了无法表示最多经过k条边，其余效率比之前的算法更快，所以<strong>适用于求存在负权值的单源最短路径问题，而无法精确为最多经过了多少条边。</strong></p>
</blockquote>
<h1 id="以题代讲">以题代讲</h1>
<h2 id="蓝桥杯--最短路">蓝桥杯&ndash;最短路</h2>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img-blog.csdnimg.cn/img_convert/591e9983075f458fe3884dd809e70b78.png"
        data-srcset="https://img-blog.csdnimg.cn/img_convert/591e9983075f458fe3884dd809e70b78.png, https://img-blog.csdnimg.cn/img_convert/591e9983075f458fe3884dd809e70b78.png 1.5x, https://img-blog.csdnimg.cn/img_convert/591e9983075f458fe3884dd809e70b78.png 2x"
        data-sizes="auto"
        alt="https://img-blog.csdnimg.cn/img_convert/591e9983075f458fe3884dd809e70b78.png"
        title="在这里插入图片描述" /></p>
<h2 id="bellman-ford的动态规划解决超时过三个">Bellman ford的动态规划解决(超时,过三个)</h2>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img-blog.csdnimg.cn/img_convert/3fcaaff49850a10cd26a01fad1fba6b8.png"
        data-srcset="https://img-blog.csdnimg.cn/img_convert/3fcaaff49850a10cd26a01fad1fba6b8.png, https://img-blog.csdnimg.cn/img_convert/3fcaaff49850a10cd26a01fad1fba6b8.png 1.5x, https://img-blog.csdnimg.cn/img_convert/3fcaaff49850a10cd26a01fad1fba6b8.png 2x"
        data-sizes="auto"
        alt="https://img-blog.csdnimg.cn/img_convert/3fcaaff49850a10cd26a01fad1fba6b8.png"
        title="在这里插入图片描述" /></p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-cpp" data-lang="cpp"><span class="cp">#include</span><span class="cpf">&lt;bits/stdc++.h&gt;</span><span class="cp">
</span><span class="cp"></span><span class="k">using</span> <span class="k">namespace</span> <span class="n">std</span><span class="p">;</span>
<span class="cp">#define LL long long
</span><span class="cp"></span><span class="kt">int</span> <span class="n">n</span><span class="p">,</span><span class="n">m</span><span class="p">;</span>
<span class="n">vector</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span><span class="n">dp</span><span class="p">(</span><span class="mi">20001</span><span class="p">,</span><span class="n">INT_MAX</span><span class="o">/</span><span class="mi">2</span><span class="p">);</span>
<span class="n">map</span><span class="o">&lt;</span><span class="kt">int</span><span class="p">,</span><span class="n">map</span><span class="o">&lt;</span><span class="kt">int</span><span class="p">,</span><span class="kt">int</span><span class="o">&gt;</span> <span class="o">&gt;</span> <span class="n">MAP</span><span class="p">;</span>
<span class="n">LL</span> <span class="nf">read</span><span class="p">()</span> <span class="p">{</span>
    <span class="n">LL</span> <span class="n">res</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="kt">bool</span> <span class="n">f</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
    <span class="kt">char</span> <span class="n">c</span><span class="p">;</span>
<span class="c1">//先耗掉一个getchar来进行判断符号
</span><span class="c1"></span>   <span class="n">c</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>
   <span class="k">if</span><span class="p">(</span><span class="n">c</span> <span class="o">==</span> <span class="sc">&#39;-&#39;</span><span class="p">)</span><span class="n">f</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">else</span> <span class="n">res</span><span class="o">+=</span> <span class="p">(</span><span class="n">c</span><span class="o">-</span><span class="sc">&#39;0&#39;</span><span class="p">);</span>

    <span class="k">while</span> <span class="p">(</span><span class="n">isdigit</span><span class="p">(</span><span class="n">c</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">()))</span> <span class="p">{</span>
        <span class="n">res</span> <span class="o">=</span> <span class="p">(</span><span class="n">LL</span><span class="p">)</span><span class="n">res</span> <span class="o">*</span> <span class="mi">10</span> <span class="o">+</span> <span class="p">(</span><span class="n">c</span><span class="o">-</span><span class="sc">&#39;0&#39;</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">f</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">res</span><span class="p">;</span>

    <span class="k">return</span> <span class="n">res</span><span class="o">*-</span><span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">(){</span>
    <span class="n">n</span> <span class="o">=</span> <span class="n">read</span><span class="p">();</span>
    <span class="n">m</span> <span class="o">=</span> <span class="n">read</span><span class="p">();</span>
    <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;</span><span class="n">m</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">){</span>
        <span class="kt">int</span> <span class="n">a</span> <span class="o">=</span><span class="n">read</span><span class="p">(),</span><span class="n">c</span> <span class="o">=</span> <span class="n">read</span><span class="p">(),</span><span class="n">len</span> <span class="o">=</span> <span class="n">read</span><span class="p">();</span>
        <span class="n">MAP</span><span class="p">[</span><span class="n">a</span><span class="p">][</span><span class="n">c</span><span class="p">]</span> <span class="o">=</span> <span class="n">len</span><span class="p">;</span>
        <span class="k">if</span><span class="p">(</span><span class="n">a</span> <span class="o">==</span> <span class="mi">1</span><span class="p">)</span>
            <span class="n">dp</span><span class="p">[</span><span class="n">c</span><span class="p">]</span> <span class="o">=</span> <span class="n">len</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="n">dp</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="n">vector</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span><span class="n">pre</span> <span class="o">=</span> <span class="n">dp</span><span class="p">;</span>
    <span class="c1">//外层循环经过最多i条路到达该结点的最短距离，最多经过n-1条
</span><span class="c1"></span>    <span class="c1">//里面几层都是用于更新没一行的数据
</span><span class="c1"></span>    <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">2</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;=</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">){</span>
        <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">j</span><span class="o">=</span><span class="mi">2</span><span class="p">;</span><span class="n">j</span><span class="o">&lt;=</span><span class="n">n</span><span class="p">;</span><span class="n">j</span><span class="o">++</span><span class="p">){</span>
            <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">k</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span><span class="n">k</span><span class="o">&lt;=</span><span class="n">n</span><span class="p">;</span><span class="n">k</span><span class="o">++</span><span class="p">){</span>
                <span class="kt">int</span> <span class="n">t</span> <span class="o">=</span> <span class="n">MAP</span><span class="p">[</span><span class="n">k</span><span class="p">][</span><span class="n">j</span><span class="p">];</span>
                <span class="k">if</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
                <span class="n">dp</span><span class="p">[</span><span class="n">j</span><span class="p">]</span> <span class="o">=</span> <span class="n">min</span><span class="p">(</span><span class="n">dp</span><span class="p">[</span><span class="n">j</span><span class="p">],</span><span class="n">pre</span><span class="p">[</span><span class="n">k</span><span class="p">]</span><span class="o">+</span><span class="n">t</span><span class="p">);</span>
            <span class="p">}</span>
        <span class="p">}</span>
        <span class="n">pre</span> <span class="o">=</span> <span class="n">dp</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">2</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;=</span><span class="n">n</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">){</span>
        <span class="n">cout</span><span class="o">&lt;&lt;</span><span class="n">dp</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">&lt;&lt;</span><span class="n">endl</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div><h2 id="bellman-ford按边遍历解决速度竟比spfa快我惊了">Bellman ford按边遍历解决(速度竟比SPFA快，我惊了)</h2>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img-blog.csdnimg.cn/img_convert/ddac0dd08b8b0d8d8898b4c0c36d40a4.png"
        data-srcset="https://img-blog.csdnimg.cn/img_convert/ddac0dd08b8b0d8d8898b4c0c36d40a4.png, https://img-blog.csdnimg.cn/img_convert/ddac0dd08b8b0d8d8898b4c0c36d40a4.png 1.5x, https://img-blog.csdnimg.cn/img_convert/ddac0dd08b8b0d8d8898b4c0c36d40a4.png 2x"
        data-sizes="auto"
        alt="https://img-blog.csdnimg.cn/img_convert/ddac0dd08b8b0d8d8898b4c0c36d40a4.png"
        title="在这里插入图片描述" /></p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-cpp" data-lang="cpp"><span class="cp">#include</span><span class="cpf">&lt;bits/stdc++.h&gt;</span><span class="cp">
</span><span class="cp"></span><span class="k">using</span> <span class="k">namespace</span> <span class="n">std</span><span class="p">;</span>
<span class="cp">#define LL long long
</span><span class="cp"></span><span class="kt">int</span> <span class="n">n</span><span class="p">,</span><span class="n">m</span><span class="p">;</span>
<span class="c1">//以边为单位遍历更新
</span><span class="c1"></span><span class="k">struct</span> <span class="nc">pos</span><span class="p">{</span>
    <span class="kt">int</span> <span class="n">i</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">j</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">len</span><span class="p">;</span>
<span class="p">};</span>
<span class="n">vector</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span><span class="n">dp</span><span class="p">(</span><span class="mi">20001</span><span class="p">,</span><span class="n">INT_MAX</span><span class="o">/</span><span class="mi">2</span><span class="p">);</span>
<span class="n">LL</span> <span class="nf">read</span><span class="p">()</span> <span class="p">{</span>
    <span class="n">LL</span> <span class="n">res</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="kt">bool</span> <span class="n">f</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
    <span class="kt">char</span> <span class="n">c</span><span class="p">;</span>
<span class="c1">//先耗掉一个getchar来进行判断符号
</span><span class="c1"></span>   <span class="n">c</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>
   <span class="k">if</span><span class="p">(</span><span class="n">c</span> <span class="o">==</span> <span class="sc">&#39;-&#39;</span><span class="p">)</span><span class="n">f</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">else</span> <span class="n">res</span><span class="o">+=</span> <span class="p">(</span><span class="n">c</span><span class="o">-</span><span class="sc">&#39;0&#39;</span><span class="p">);</span>

    <span class="k">while</span> <span class="p">(</span><span class="n">isdigit</span><span class="p">(</span><span class="n">c</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">()))</span> <span class="p">{</span>
        <span class="n">res</span> <span class="o">=</span> <span class="p">(</span><span class="n">LL</span><span class="p">)</span><span class="n">res</span> <span class="o">*</span> <span class="mi">10</span> <span class="o">+</span> <span class="p">(</span><span class="n">c</span><span class="o">-</span><span class="sc">&#39;0&#39;</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">f</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">res</span><span class="p">;</span>

    <span class="k">return</span> <span class="n">res</span><span class="o">*-</span><span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">(){</span>
    <span class="n">n</span> <span class="o">=</span> <span class="n">read</span><span class="p">();</span>
    <span class="n">m</span> <span class="o">=</span> <span class="n">read</span><span class="p">();</span>
    <span class="c1">//记录m条边的关系
</span><span class="c1"></span>    <span class="n">pos</span> <span class="n">MAP</span><span class="p">[</span><span class="n">m</span><span class="p">];</span>
    <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;</span><span class="n">m</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">){</span>
        <span class="kt">int</span> <span class="n">a</span> <span class="o">=</span><span class="n">read</span><span class="p">(),</span><span class="n">c</span> <span class="o">=</span> <span class="n">read</span><span class="p">(),</span><span class="n">len</span> <span class="o">=</span> <span class="n">read</span><span class="p">();</span>
        <span class="n">MAP</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="p">{</span><span class="n">a</span><span class="p">,</span><span class="n">c</span><span class="p">,</span><span class="n">len</span><span class="p">};</span>
    <span class="p">}</span>
    <span class="n">dp</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="c1">//外面一层代表遍历边的次数，最多为n-1次
</span><span class="c1"></span>    <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">1</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;=</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">){</span>
			<span class="kt">bool</span> <span class="n">flag</span> <span class="o">=</span> <span class="nb">true</span><span class="p">;</span>
        <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">k</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="n">k</span><span class="o">&lt;</span><span class="n">m</span><span class="p">;</span><span class="n">k</span><span class="o">++</span><span class="p">){</span>
            <span class="k">if</span><span class="p">(</span><span class="n">dp</span><span class="p">[</span><span class="n">MAP</span><span class="p">[</span><span class="n">k</span><span class="p">].</span><span class="n">j</span><span class="p">]</span><span class="o">&gt;</span><span class="n">dp</span><span class="p">[</span><span class="n">MAP</span><span class="p">[</span><span class="n">k</span><span class="p">].</span><span class="n">i</span><span class="p">]</span><span class="o">+</span><span class="n">MAP</span><span class="p">[</span><span class="n">k</span><span class="p">].</span><span class="n">len</span><span class="p">){</span>
                <span class="n">dp</span><span class="p">[</span><span class="n">MAP</span><span class="p">[</span><span class="n">k</span><span class="p">].</span><span class="n">j</span><span class="p">]</span> <span class="o">=</span> <span class="n">dp</span><span class="p">[</span><span class="n">MAP</span><span class="p">[</span><span class="n">k</span><span class="p">].</span><span class="n">i</span><span class="p">]</span><span class="o">+</span><span class="n">MAP</span><span class="p">[</span><span class="n">k</span><span class="p">].</span><span class="n">len</span><span class="p">;</span>
                <span class="n">flag</span> <span class="o">=</span> <span class="nb">false</span><span class="p">;</span>
            <span class="p">}</span>
        <span class="p">}</span>
        <span class="c1">//一旦有一轮遍历未更新一次，则弹出循环，得出答案
</span><span class="c1"></span>        <span class="k">if</span><span class="p">(</span><span class="n">flag</span><span class="p">)</span>
            <span class="k">break</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">2</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;=</span><span class="n">n</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">){</span>
        <span class="n">cout</span><span class="o">&lt;&lt;</span><span class="n">dp</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">&lt;&lt;</span><span class="n">endl</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>

</code></pre></div><h2 id="最终优化--spfa算法">最终优化&ndash;SPFA算法</h2>
<blockquote>
<p>毕竟SPFA的全称为Shortest Path Faster Algorithm，也得当担得起这个名字啊🤣</p>
</blockquote>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://img-blog.csdnimg.cn/img_convert/9d30ebb384930d3bba92604f0b26dfba.png"
        data-srcset="https://img-blog.csdnimg.cn/img_convert/9d30ebb384930d3bba92604f0b26dfba.png, https://img-blog.csdnimg.cn/img_convert/9d30ebb384930d3bba92604f0b26dfba.png 1.5x, https://img-blog.csdnimg.cn/img_convert/9d30ebb384930d3bba92604f0b26dfba.png 2x"
        data-sizes="auto"
        alt="https://img-blog.csdnimg.cn/img_convert/9d30ebb384930d3bba92604f0b26dfba.png"
        title="在这里插入图片描述" /></p>
<blockquote>
<p>主要因为用STL容器存储数据的原因，所以似乎稍慢。</p>
</blockquote>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-cpp" data-lang="cpp"><span class="cp">#include</span><span class="cpf">&lt;bits/stdc++.h&gt;</span><span class="cp">
</span><span class="cp"></span><span class="k">using</span> <span class="k">namespace</span> <span class="n">std</span><span class="p">;</span>
<span class="cp">#define LL long long
</span><span class="cp"></span><span class="kt">int</span> <span class="n">n</span><span class="p">,</span><span class="n">m</span><span class="p">;</span>
<span class="c1">//以边为单位遍历更新,再进一步优化便得到得到SPFA算法
</span><span class="c1">//我们需要构造一个以任一点为起点的，它所连接的通路的结构，以方便队列进行操作，用哈希表进行映射最好
</span><span class="c1"></span><span class="n">map</span><span class="o">&lt;</span><span class="kt">int</span><span class="p">,</span><span class="n">vector</span><span class="o">&lt;</span><span class="n">pair</span><span class="o">&lt;</span><span class="kt">int</span><span class="p">,</span><span class="kt">int</span><span class="o">&gt;</span> <span class="o">&gt;</span> <span class="o">&gt;</span><span class="n">MAP</span><span class="p">;</span>
<span class="n">vector</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span><span class="n">dp</span><span class="p">(</span><span class="mi">20001</span><span class="p">,</span><span class="n">INT_MAX</span><span class="o">/</span><span class="mi">2</span><span class="p">);</span>
<span class="n">queue</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span><span class="n">Q</span><span class="p">;</span>
<span class="c1">//标记结点是否在队列之中
</span><span class="c1"></span><span class="kt">bool</span> <span class="n">check</span><span class="p">[</span><span class="mi">20001</span><span class="p">]</span> <span class="o">=</span> <span class="p">{</span><span class="nb">false</span><span class="p">};</span>
<span class="n">LL</span> <span class="nf">read</span><span class="p">()</span> <span class="p">{</span>
    <span class="n">LL</span> <span class="n">res</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="kt">bool</span> <span class="n">f</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
    <span class="kt">char</span> <span class="n">c</span><span class="p">;</span>
<span class="c1">//先耗掉一个getchar来进行判断符号
</span><span class="c1"></span>   <span class="n">c</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">();</span>
   <span class="k">if</span><span class="p">(</span><span class="n">c</span> <span class="o">==</span> <span class="sc">&#39;-&#39;</span><span class="p">)</span><span class="n">f</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">else</span> <span class="n">res</span><span class="o">+=</span> <span class="p">(</span><span class="n">c</span><span class="o">-</span><span class="sc">&#39;0&#39;</span><span class="p">);</span>

    <span class="k">while</span> <span class="p">(</span><span class="n">isdigit</span><span class="p">(</span><span class="n">c</span> <span class="o">=</span> <span class="n">getchar</span><span class="p">()))</span> <span class="p">{</span>
        <span class="n">res</span> <span class="o">=</span> <span class="p">(</span><span class="n">LL</span><span class="p">)</span><span class="n">res</span> <span class="o">*</span> <span class="mi">10</span> <span class="o">+</span> <span class="p">(</span><span class="n">c</span><span class="o">-</span><span class="sc">&#39;0&#39;</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">f</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">res</span><span class="p">;</span>

    <span class="k">return</span> <span class="n">res</span><span class="o">*-</span><span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">(){</span>
    <span class="n">n</span> <span class="o">=</span> <span class="n">read</span><span class="p">();</span>
    <span class="n">m</span> <span class="o">=</span> <span class="n">read</span><span class="p">();</span>
    <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;</span><span class="n">m</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">){</span>
        <span class="kt">int</span> <span class="n">a</span> <span class="o">=</span><span class="n">read</span><span class="p">(),</span><span class="n">c</span> <span class="o">=</span> <span class="n">read</span><span class="p">(),</span><span class="n">len</span> <span class="o">=</span> <span class="n">read</span><span class="p">();</span>
        <span class="n">MAP</span><span class="p">[</span><span class="n">a</span><span class="p">].</span><span class="n">push_back</span><span class="p">(</span><span class="n">make_pair</span><span class="p">(</span><span class="n">c</span><span class="p">,</span><span class="n">len</span><span class="p">));</span>
    <span class="p">}</span>
    <span class="n">dp</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="n">Q</span><span class="p">.</span><span class="n">push</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
    <span class="n">check</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="nb">true</span><span class="p">;</span>
    <span class="k">while</span><span class="p">(</span><span class="o">!</span><span class="n">Q</span><span class="p">.</span><span class="n">empty</span><span class="p">()){</span>
        <span class="kt">int</span> <span class="n">node</span> <span class="o">=</span> <span class="n">Q</span><span class="p">.</span><span class="n">front</span><span class="p">();</span><span class="n">Q</span><span class="p">.</span><span class="n">pop</span><span class="p">();</span><span class="n">check</span><span class="p">[</span><span class="n">node</span><span class="p">]</span> <span class="o">=</span> <span class="nb">false</span><span class="p">;</span>
        <span class="n">vector</span><span class="o">&lt;</span><span class="n">pair</span><span class="o">&lt;</span><span class="kt">int</span><span class="p">,</span><span class="kt">int</span><span class="o">&gt;</span> <span class="o">&gt;&amp;</span> <span class="n">t</span> <span class="o">=</span> <span class="n">MAP</span><span class="p">[</span><span class="n">node</span><span class="p">];</span>
        <span class="c1">//以node为起点开始更新，一旦被更新且队中无该结点，则入队。
</span><span class="c1"></span>        <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;</span><span class="n">t</span><span class="p">.</span><span class="n">size</span><span class="p">();</span><span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span><span class="p">(</span><span class="n">dp</span><span class="p">[</span><span class="n">t</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">first</span><span class="p">]</span><span class="o">&gt;</span><span class="n">dp</span><span class="p">[</span><span class="n">node</span><span class="p">]</span><span class="o">+</span><span class="n">t</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">second</span><span class="p">){</span>
                <span class="n">dp</span><span class="p">[</span><span class="n">t</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">first</span><span class="p">]</span> <span class="o">=</span> <span class="n">dp</span><span class="p">[</span><span class="n">node</span><span class="p">]</span><span class="o">+</span><span class="n">t</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">second</span><span class="p">;</span>
                <span class="c1">//入队操作
</span><span class="c1"></span>                <span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">check</span><span class="p">[</span><span class="n">t</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">first</span><span class="p">])</span>
                    <span class="n">Q</span><span class="p">.</span><span class="n">push</span><span class="p">(</span><span class="n">t</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">first</span><span class="p">);</span>
                    <span class="n">check</span><span class="p">[</span><span class="n">t</span><span class="p">[</span><span class="n">i</span><span class="p">].</span><span class="n">first</span><span class="p">]</span> <span class="o">=</span> <span class="nb">true</span><span class="p">;</span>
            <span class="p">}</span>
        <span class="p">}</span>
    <span class="p">}</span>


    <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">2</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;=</span><span class="n">n</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">){</span>
        <span class="n">cout</span><span class="o">&lt;&lt;</span><span class="n">dp</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">&lt;&lt;</span><span class="n">endl</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div><div class="post-footer" id="post-footer">
    <div class="post-info"><div class="post-info-tag"><span><a href="/tags/bellmanford%E5%92%8Cspfa%E7%AE%97%E6%B3%95%E8%AF%A6%E8%A7%A3/">BellmanFord和SPFA算法详解</a>
                </span></div><div class="post-info-line"><div class="post-info-mod">
                <span>更新于 2022-02-07</span>
            </div><div class="post-info-mod"></div>
        </div><div class="post-info-share">
            <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://acking-you.github.io/posts/bellmanford%E5%92%8Cspfa%E7%AE%97%E6%B3%95%E8%AF%A6%E8%A7%A3/" data-title="BellmanFord和SPFA算法详解" data-hashtags="BellmanFord和SPFA算法详解"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://acking-you.github.io/posts/bellmanford%E5%92%8Cspfa%E7%AE%97%E6%B3%95%E8%AF%A6%E8%A7%A3/" data-hashtag="BellmanFord和SPFA算法详解"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 WhatsApp" data-sharer="whatsapp" data-url="https://acking-you.github.io/posts/bellmanford%E5%92%8Cspfa%E7%AE%97%E6%B3%95%E8%AF%A6%E8%A7%A3/" data-title="BellmanFord和SPFA算法详解" data-web><i class="fab fa-whatsapp fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://acking-you.github.io/posts/bellmanford%E5%92%8Cspfa%E7%AE%97%E6%B3%95%E8%AF%A6%E8%A7%A3/" data-title="BellmanFord和SPFA算法详解"><i class="fab fa-line fa-fw"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://acking-you.github.io/posts/bellmanford%E5%92%8Cspfa%E7%AE%97%E6%B3%95%E8%AF%A6%E8%A7%A3/" data-title="BellmanFord和SPFA算法详解" data-image="https://img-blog.csdnimg.cn/img_convert/6a656bf83ac631cc9afaeaef07661809.png"><i class="fab fa-weibo fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Myspace" data-sharer="myspace" data-url="https://acking-you.github.io/posts/bellmanford%E5%92%8Cspfa%E7%AE%97%E6%B3%95%E8%AF%A6%E8%A7%A3/" data-title="BellmanFord和SPFA算法详解" data-description="BellmanFord和SPFA算法详解"><i data-svg-src="/lib/simple-icons/icons/myspace.min.svg"></i></a><a href="javascript:void(0);" title="分享到 Blogger" data-sharer="blogger" data-url="https://acking-you.github.io/posts/bellmanford%E5%92%8Cspfa%E7%AE%97%E6%B3%95%E8%AF%A6%E8%A7%A3/" data-title="BellmanFord和SPFA算法详解" data-description="BellmanFord和SPFA算法详解"><i class="fab fa-blogger fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Evernote" data-sharer="evernote" data-url="https://acking-you.github.io/posts/bellmanford%E5%92%8Cspfa%E7%AE%97%E6%B3%95%E8%AF%A6%E8%A7%A3/" data-title="BellmanFord和SPFA算法详解"><i class="fab fa-evernote fa-fw"></i></a></span>
        </div></div><div class="post-nav"><a href="/posts/dijkstra%E7%AE%97%E6%B3%95%E6%A8%A1%E6%9D%BF%E8%AE%B2%E8%A7%A3/" class="prev" rel="prev" title="Dijkstra算法模板讲解"><i class="fas fa-angle-left fa-fw"></i>Previous Post</a>
            <a href="/posts/%E6%95%B0%E6%8D%AE%E5%BA%93%E5%9F%BA%E7%A1%80/" class="next" rel="next" title="数据库基础">Next Post<i class="fas fa-angle-right fa-fw"></i></a></div></div>
</div></article></div>
            </main>
            <footer class="footer"><div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.86.0">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/khusika/FeelIt" target="_blank" rel="noopener noreffer" title="FeelIt 1.0.1"><i class="fas fa-hand-holding-heart fa-fw"></i> FeelIt</a>
        </div><div class="footer-line" itemscope itemtype="http://schema.org/CreativeWork"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2023</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/"></a></span></div>
</div>
</footer>
        </div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-chevron-up fa-fw"></i>
            </a></div><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><link rel="stylesheet" href="/lib/katex/katex.min.css"><link rel="stylesheet" href="/lib/katex/copy-tex.min.css"><script src="/lib/autocomplete/autocomplete.min.js"></script><script src="/lib/lunr/lunr.min.js"></script><script src="/lib/lunr/lunr.stemmer.support.min.js"></script><script src="/lib/lunr/lunr.zh.min.js"></script><script src="/lib/lazysizes/lazysizes.min.js"></script><script src="/lib/clipboard/clipboard.min.js"></script><script src="/lib/sharer/sharer.min.js"></script><script src="/lib/katex/katex.min.js"></script><script src="/lib/katex/auto-render.min.js"></script><script src="/lib/katex/copy-tex.min.js"></script><script src="/lib/katex/mhchem.min.js"></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":200},"comment":{},"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":100,"noResultsFound":"没有找到结果","snippetLength":50,"type":"lunr"}};</script><script src="/js/theme.min.js"></script></body></html>
